<?php
/**
 * 商品管理
*
* @author karl <karl.tang@aiyuangong.com>
* @link http://www.aiyuangong.com
*/
namespace app\admin\controller\goods;

use app\admin\Controller;
use think\Db;
use think\helper\Str;

class GoodsCommon extends Controller
{
    use\app\admin\traits\controller\Controller;

    protected static $blacklist = [
        'deleteforever',
        'clear'
    ];

    public function index() {
        //$where = ['status'=>1,'isdelete'=>0];
        $goods_name = $this->request->param('goods_name');
        $goods_serial = $this->request->param('goods_serial');
        $store_name = $this->request->param('store_name');
        $goods_state= $this->request->param('goods_state');
        $goods_verify = $this->request->param('goods_verify');
        $where = [];
        if($goods_name){
            $where['goods_name'] = ['like','%'.$goods_name.'%'];
        }
        if($goods_serial){
            $where['goods_serial'] = ['like','%'.$goods_serial.'%'];
        }
        if($store_name){
            $where['store_name'] = ['like','%'.$store_name.'%'];
        }
        if(isset($goods_state) && $goods_state != ''){
            $where['goods_state'] = $goods_state;
        }
        if(isset($goods_verify) && $goods_verify != ''){
            $where['goods_verify'] = $goods_verify;
        }
        if ($this::$isdelete !== false) {
            $where['isdelete'] = $this::$isdelete;
        }
        //商品列表
        $list = $this->datalist(model('goods_common'), $where, '*', '', false, true);
        foreach($list as $key => $val){
            $str .= $val['id'].',';
        }
        $goodsid_list = Db::name('goods')->where('commonid','in','('.trim($str,',').')')->field('commonid,id')->group('commonid')->select();
        $goodsid_list = reset_by_key($goodsid_list, 'commonid');
        // 分类列表
        $rs = \Fields::getById("goods_class");
        $rs = reset_by_key($rs, 'id');
        foreach ($rs as $k => $v) {
            $rs[$k]['_child'] = reset_by_key($v['_child'], 'id');
        }
        $classList = $rs;
        $stateList = [GOODS_STATE_ON =>'出售中',GOODS_STATE_OUT=>'正常下架',GOODS_STATE_OUT_LINE=>'违规下架'];//审核状态
        $verifyList = [GOODS_VERIFY_PASS=>'审核通过',GOODS_VERIFY_FAIL=>'审核失败',GOODS_VERIFY_WAIT=>'等待审核'];//审核状态
        $verify = request()->param('goods_verify');
        $state = request()->param('goods_state');
        // 模板赋值显示
        $this->view->assign('list', $list);
        $this->view->assign("count", $list->total());
        $this->view->assign('goodsid_list', $goodsid_list);
        $this->view->assign('state', $state);
        $this->view->assign('verify', $verify);
        $this->view->assign('state_list', $stateList);
        $this->view->assign('verify_list', $verifyList);
        $this->view->assign('class_list', $classList);
        $this->view->assign('is_verify', config('goods_verify')); // 是否开启审核
        return $this->view->fetch();
    }

    /**
     * 商品审核
     */
    public function audit() {
        $id = $this->request->param('id/d', 0);
        if ($this->request->isPost()) {
            $state = $this->request->param('state/s', ''); //审核状态success  fail\
            if ($state == 'success') {
                //审核成功，商品上架
                $data['goods_verify'] = GOODS_VERIFY_PASS;
                $data['goods_state'] = GOODS_STATE_ON;
            } else {
                $data['goods_verify'] = GOODS_VERIFY_FAIL;
                $data['goods_state'] = GOODS_STATE_OUT;
            }
            try {
                $result = Db::name('goods')->where([
                            'commonid' => $id
                        ])->update($data);
                $data['goods_verifyremark'] = $this->request->param('remark/s', '');
                $result = Db::name('goods_common')->where([
                            'id' => $id
                        ])->update($data);
                if ($result !== false) {
                    return ajax_return_adv('商品已审核');
                } else {
                    return ajax_return_adv_error('操作失败');
                }
            } catch (Exception $e) {
                throw new Exception($e->getMessage());
            }
        } else {
            // 编辑页
            $this->view->assign('id', $id);
            return $this->view->fetch();
        }
    }

    /**
     * 商品下架
     */
    public function off_sale() {
        $id = $this->request->param('id/d', 0);
        if ($this->request->isPost()) {
            $data['goods_state'] = GOODS_STATE_OUT_LINE;
            try {
                $result = Db::name('goods')->where([
                            'commonid' => $id
                        ])->update(['goods_state' => GOODS_STATE_OUT_LINE]);
                $data['goods_stateremark'] = $this->request->param('remark/s', '');
                $result = Db::name('goods_common')->where([
                            'id' => $id
                        ])->update($data);
                if ($result !== false) {
                    // 商品违规下架发送店铺消息
                    $common_info = Db::name('goods_common')->where(['id' => $id])->find();
                    if(!empty($common_info)){
                        $param = [];
                        $param['remark'] = $this->request->param('remark/s', '');
                        $param['common_id'] = $id;
                        model("Common/Queue", "logic")->sendStoreMsg(['code' => 'goods_violation', 'store_id' => $common_info['store_id'], 'param' => $param]);
                    }
                    return ajax_return_adv('商品已下架');
                } else {
                    return ajax_return_adv_error('操作失败');
                }
            } catch (Exception $e) {
                throw new Excption($e->getMessage());
            }
        } else {
            // 编辑页
            $this->view->assign('id', $id);
            return $this->view->fetch();
        }
    }

    /**
     * 子商品列表
     */
    public function goods_list() {
        $commonid = $this->request->param('id/d', 0);
        if ($commonid <= 0) {
            return ajax_return_adv_error('参数异常');
        }
        $goodscommon_list = Db::name('goods_common')->where(['id' => $commonid])->field('spec_name')->find();
        if (empty($goodscommon_list)) {
            return ajax_return_adv_error('没有商品记录');
        }
        $goods_list = Db::name('goods')->where(['commonid' => $commonid])->field('id,goods_serial,goods_spec,goods_image,goods_price,goods_storage')->select();
        if (empty($goods_list)) {
            return ajax_return_adv_error('没有子商品记录');
        }
        $spec_name = array_values((array) unserialize($goodscommon_list['spec_name']));
        foreach ($goods_list as $key => $val) {
            $goods_spec = array_values((array) unserialize($val['goods_spec']));
            $spec_array = array();
            foreach ($goods_spec as $k => $v) {
                $spec_array[] = '<div class="goods_spec">' . $spec_name[$k] . '：<em title="' . $v . '">' . $v . '</em>' . '</div>';
            }
            $goods_list[$key]['goods_image'] = img_url($val['goods_image'], 60);
            $goods_list[$key]['goods_spec'] = implode('', $spec_array);
            $goods_list[$key]['url'] = url('index/goods/detail', ['goods_id' => $val['id']]);
        }
        return json(["code" => 0, "msg" => '', "data" => $goods_list]);
    }
    
    /**
     * 获取品牌筛选信息
     */
    public function brand_select() {
        // 品牌列表
        $type = $this->request->param('type/s', '');
        $where = [
            'isdelete' => 0, 'status' => 1
        ];
        if ($type == 'letter') {
            $letter = $this->request->param('letter/s', '');
            $where['initial'] = Str::upper($letter);
        } else {
            $keyword = $this->request->param('keyword/s', '');
            $where['name'] = ['like', $keyword];
        }
        $brandList = Db::name('goods_brand')->where($where)->field('id as brand_id,name as brand_name,initial as brand_initial')->order('initial asc , sort asc')->select();
        return json($brandList);
    }

}